<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * general
 *
 * @author Simon Emms <simon@simonemms.com>
 */
class general_form extends MY_Form {



    
    
    /**
     * Login
     * 
     * Gets the site login
     * 
     * @return array
     */
    public function login() {
        
        /* Load stuff */
        //$this->load->library('ssh');
        $this->load->model('database');
        $this->load->model('connections');
        
        /* Get the database types */
        $arrTypes = $this->database->get_db_types();
        
        $arrSaved = array();
        $login = false;
        
        /* Get the saved connections */
        if($this->api_connect->can_connect()) {
            if($this->api_connect->is_logged_in()) {
                $arrSaved = $this->connections->get_saved_connections();
            }
        }
        
        $arrForm = array();
        
        $arrForm['form_login'] = array(
            array(
                'name' => 'type',
                'type' => 'form_dropdown',
                'label' => $this->lang->line('database_type'),
                'rules' => 'required',
                'options' => $arrTypes,
                'value'=> '',
            ),
            array(
                'name' => 'name',
                'type' => 'form_input', 
                'label' => $this->lang->line('database_name'),
                'rules' => 'required',
                'value' => $this->lang->line('database_default_name'),
            ),
            array(
                'name' => 'host',
                'type' => 'form_input', 
                'label' => $this->lang->line('database_host'),
                'rules' => 'required',
                'value' => 'localhost', /* localhost by default */
            ),
            array(
                'name' => 'username',
                'type' => 'form_input',
                'label' => $this->lang->line('database_username'),
                'rules' => '',
            ),
            array(
                'name' => 'password',
                'type' => 'form_password',
                'label' => $this->lang->line('database_password'),
                'rules' => '',
            ),
            array(
                'name' => 'port',
                'type' => 'form_input',
                'label' => $this->lang->line('database_port'),
                'rules' => 'is_natural',
                'maxlength' => 5,
            ),
        );
        
        if(count($arrSaved) > 0) {
            /* There's some saved connections */
            $arrSaved = $this->connections->encode($arrSaved);
            
            /* Put it in the format we need here */
            $arrConnection = array();
            if(is_array($arrSaved) && count($arrSaved) > 0) {
                foreach($arrSaved as $saved) {
                    $arrConnection[$saved['key']] = $saved['name'];
                }
            }
            
            /* Double check the array */
            if(count($arrConnection) > 0) {
                /* Order by name */
                asort($arrConnection);
                
                array_unshift($arrForm['form_login'], array(
                    'name' => 'connection',
                    'type' => 'form_dropdown',
                    'label' => $this->lang->line('database_connections'),
                    'rules' => '',
                    'options' => $arrConnection,
                    'add_select' => true,
                ));
            }
        }
        
        /* SSH Connection *
        $arrForm['form_ssh'] = array(
            array(
                'name' => 'ssh_host',
                'type' => 'form_input',
                'label' => $this->lang->line('database_ssh_host'),
                'value' => '',
            ),
            array(
                'name' => 'ssh_username',
                'type' => 'form_input',
                'label' => $this->lang->line('database_ssh_username'),
                'value' => '',
            ),
            array(
                'name' => 'ssh_password',
                'type' => 'form_input',
                'label' => $this->lang->line('database_ssh_password'),
                'value' => '',
            ),
            array(
                'name' => 'ssh_port',
                'type' => 'form_input',
                'label' => $this->lang->line('database_ssh_port'),
                'value' => '',
            ),
        );*/

        /* Set the form */
        foreach($arrForm as $name => $value) {
            $this->set_fields($value, $name);
        }

        /* Set the buttons */
        $this->add_button('submit', $this->lang->line('action_menu_login'));

        /* Activate the form */
        if($this->activate()) {

            /**
             * This is where any validation rules that
             * are not part of the default CI things - in
             * this example, this would be where you validate
             * the login credentials in the database.
             */
            
            /* Get the form data */
            $arrData = $this->get_details();
            
            /* Trying to connect to a saved connection */
            if(array_key_exists('connection', $arrData)) {
                
                $arrConnection = $this->connections->decode($arrData['connection']);
                
                if($arrConnection !== false) {
                    /* Valid connection - use it */
                    foreach($arrConnection as $key => $value) {
                        /* Replace the form */
                        $arrData[$key] = $value;
                        
                        /* Replace the POST - required to make the run() validate */
                        $_POST[$key] = $value;
                    }
                }
            
            }
            
            /* Unset the connection */
            unset($arrData['connection']);
            
            /* Check that a DB type is set (no error needed as it's required) */
            if(in_array($arrData['type'], array_keys($arrTypes))) {
                /* Try and connect to the database */
                $connection_id = $this->database->verify_login($arrData['username'], $arrData['password'], $arrData['host'], $arrData['type'], $arrData['port']);
                if($connection_id === false) {
                    /* Failed to connect - find the reason */
                    if(function_exists($this->db->connection)) {
                        $this->set_error('database', 'database_connection_failed');
                    } else {
                        $this->set_error('database', $this->lang->line('db_function_not_exist', array('%f' => $this->db->connection)));
                    }
                }
            }
            
            /* Validate the form */
            if($this->run()) {

                /**
                 * This is where you would put what happens
                 * AFTER we have validated the form. Don't
                 * forget to redirect to remove the POST
                 * headers
                 */
                
                /* Save the connection */
                $this->database->save_connection($connection_id, $arrData['username'], $arrData['password'], $arrData['host'], $arrData['type'], $arrData['port'], $arrData['name']);
                
                /* Find the redirect */
                $redirect = $this->session->userdata($this->config->item('session_redirect'));
                if($redirect === false) { $redirect = site_url(); }
                
                redirect($redirect);
            }
        }

        /* Get the form for display */
        $arrFields = array();
        foreach($arrForm as $name => $value) {
            $arrFields[$name] = $this->get_fields($name);
        }
        return $arrFields;
    }
    
    
    
    
    
    
    
    /**
     * New Connection
     * 
     * Allows a new database connection
     * to be made
     * 
     * @return array
     */
    public function new_connection() {
        
        /* Load stuff */
        $this->load->model('database');
        $this->load->model('connections');
        
        /* Get the database types */
        $arrTypes = $this->database->get_db_types();
        
        /* Get the saved connections */
        $arrSaved = $this->connections->get_saved_connections(true);
        
        $arrForm = array(
            array(
                'name' => 'type',
                'type' => 'form_dropdown',
                'label' => $this->lang->line('database_type'),
                'rules' => 'required',
                'options' => $arrTypes,
                'value'=> '',
            ),
            array(
                'name' => 'name',
                'type' => 'form_input', 
                'label' => $this->lang->line('database_name'),
                'rules' => 'required',
                'value' => $this->lang->line('database_default_name'),
            ),
            array(
                'name' => 'host',
                'type' => 'form_input', 
                'label' => $this->lang->line('database_host'),
                'rules' => 'required',
                'value' => 'localhost', /* localhost by default */
            ),
            array(
                'name' => 'username',
                'type' => 'form_input',
                'label' => $this->lang->line('database_username'),
                'rules' => '',
            ),
            array(
                'name' => 'password',
                'type' => 'form_password',
                'label' => $this->lang->line('database_password'),
                'rules' => '',
            ),
            array(
                'name' => 'port',
                'type' => 'form_input',
                'label' => $this->lang->line('database_port'),
                'rules' => 'is_natural',
                'maxlength' => 5,
            ),
        );
        
        if(count($arrSaved) > 0) {
            /* There's some saved connections */
            $arrSaved = $this->connections->encode($arrSaved);
            
            /* Put it in the format we need here */
            $arrConnection = array();
            if(is_array($arrSaved) && count($arrSaved) > 0) {
                foreach($arrSaved as $saved) {
                    $arrConnection[$saved['key']] = $saved['name'];
                }
            }
            
            /* Double check the array */
            if(count($arrConnection) > 0) {
                array_unshift($arrForm, array(
                    'name' => 'connection',
                    'type' => 'form_dropdown',
                    'label' => $this->lang->line('database_connections'),
                    'rules' => '',
                    'options' => $arrConnection,
                    'add_select' => true,
                ));
            }
        }

        /* Set the form */
        $this->set_fields($arrForm);

        /* Set the buttons */
        $this->add_button('submit', $this->lang->line('action_menu_login'));

        /* Activate the form */
        if($this->activate()) {

            /**
             * This is where any validation rules that
             * are not part of the default CI things - in
             * this example, this would be where you validate
             * the login credentials in the database.
             */
            
            /* Get the form data */
            $arrForm = $this->get_details();
            
            /* Trying to connect to a saved connection */
            if(array_key_exists('connection', $arrForm)) {
                
                $arrConnection = $this->connections->decode($arrForm['connection']);
                
                if($arrConnection !== false) {
                    /* Valid connection - use it */
                    foreach($arrConnection as $key => $value) {
                        /* Replace the form */
                        $arrForm[$key] = $value;
                        
                        /* Replace the POST - required to make the run() validate */
                        $_POST[$key] = $value;
                    }
                }
            
            }
            
            /* Unset the connection */
            unset($arrForm['connection']);
            
            /* Check that a DB type is set (no error needed as it's required) */
            if(in_array($arrForm['type'], array_keys($arrTypes))) {
                /* Try and connect to the database */
                $connection_id = $this->database->verify_login($arrForm['username'], $arrForm['password'], $arrForm['host'], $arrForm['type'], $arrForm['port']);
                if($connection_id === false) {
                    /* Failed to connect - find the reason */
                    if(function_exists($this->db->connection)) {
                        $this->set_error('database', 'database_connection_failed');
                    } else {
                        $this->set_error('database', $this->lang->line('db_function_not_exist', array('%f' => $this->db->connection)));
                    }
                }
            }
            
            /* Validate the form */
            if($this->run()) {

                /**
                 * This is where you would put what happens
                 * AFTER we have validated the form. Don't
                 * forget to redirect to remove the POST
                 * headers
                 */
                
                /* Save the connection */
                $this->database->save_connection($connection_id, $arrForm['username'], $arrForm['password'], $arrForm['host'], $arrForm['type'], $arrForm['port'], $arrForm['name']);
                
                /* Find the redirect */
                //$redirect = $this->session->getSession($this->config->item('session_redirect'));
                //if($redirect === false) { $redirect = site_url(); }
                
                redirect($this->input->rest_replace($this->config->item('connection', 'rest'), $connection_id, site_url()));
                
            }
        }

        /* Get the form for display */
        return $this->get_fields();
        
    }
    
    
    
    
    
    
    
    
    /**
     * Language
     * 
     * Get the the language select form
     * 
     * @return array
     */
    public function language() {
        
        /* Load stuff */
        $arrConfig = $this->config->item('languages');
        
        $arrLangs = array();
        if(count($arrConfig) > 0) {
            foreach($arrConfig as $key) {
                $lang = $this->config->item($key.'_lang', 'lang_name');
                
                if($lang !== false) { $arrLangs[$key] = $lang; }
            }
        }
        
        /* No point in displaying if only one language */
        if(count($arrLangs) > 1) {
            
            asort($arrLangs);
        
            $arrForm = array(
                array(
                    'name' => 'language_select',
                    //'label' => $this->lang->line('language_select'),
                    'type' => 'form_dropdown',
                    'value' => $this->config->item('language'),
                    'options' => $arrLangs,
                    'add_select' => false,
                ),
            );

            /* Set the form */
            $this->set_fields($arrForm);

            /* Set the buttons */
            $this->add_button('submit', $this->lang->line('action_menu_go'));

            /* Activate the form */
            if($this->activate()) {

                /**
                * This is where any validation rules that
                * are not part of the default CI things - in
                * this example, this would be where you validate
                * the login credentials in the database.
                */

                /* Get the form data */
                $arrForm = $this->get_details();

                /* Validate the form */
                if($this->run()) {

                    /**
                    * This is where you would put what happens
                    * AFTER we have validated the form. Don't
                    * forget to redirect to remove the POST
                    * headers
                    */
                    
                    /* Find the new URL */
                    $url = $this->lang->change_language($arrForm['language_select']);
                    
                    /* If error, go to same page */
                    if($url === false) { $url = current_url(); }
                    
                    /* Go to page */
                    redirect($url);

                }

            }

            /* Get the form for display */
            return $this->get_fields();
        }
        
    }
    
    
    
    
    
    
    
    
    /**
     * SQL Query
     * 
     * Generates a form so we can execute a SQL query
     * 
     * @return array
     */
    public function sql_query($query = null) {
        
        /* Load stuff */
        $this->load->model('database');
        
        $arrForm = array(
            'connections' => array(
                array(
                    'name' => 'sql_connection',
                    'label' => $this->lang->line('database_select'),
                    'type' => 'form_dropdown',
                    'value' => $this->input->rest($this->config->item('database', 'rest')),
                    'options' => $this->database->fetch_databases(true),
                ),
            ),
            'query' => array(
                array(
                    'name' => 'sql_query',
                    'type' => 'form_textarea',
                    'value' => urldecode($query),
                ),
                array(
                    'name' => 'connection_id',
                    'id' => 'connection_id',
                    'type' => 'form_hidden',
                    'value' => $this->database->db(true),
                )
            ),
        );

        /* Set the form */
        foreach($arrForm as $name => $value) {
            $this->set_fields($value, $name);
        }

        /* Set the buttons */
        $this->add_button('submit', $this->lang->line('sql_query_exec'), 'submit', 'sql_query_exec');

        /* Activate the form */
        if($this->activate()) {
            
            /* Get the form data */
            $arrDetails = $this->get_details();
            
            /* Validate the form */
            if($this->run()) {
                
                /* Connection */
                $url = $this->input->rest_replace($this->config->item('connection', 'rest'), $arrDetails['connection_id']);
                
                /* Database */
                $url = $this->input->rest_replace($this->config->item('database', 'rest'), $arrDetails['sql_connection'], $url);
                
                /* Query - double URL encode this */
                $url = $this->input->rest_replace($this->config->item('query', 'rest'), urlencode($arrDetails['sql_query']), $url);
                
                /* Redirect to the query page */
                redirect($url);
                
            }
        }
        
        $arrReturn = array();
        foreach($arrForm as $name => $value) {
            $arrReturn[$name] = $this->get_fields($name);
        }
        
        return $arrReturn;
    }
    


}
?>